package com.atguigu.gmall.order.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.bean.UserInfo;
import com.atguigu.gmall.common.exception.OrderException;
import com.atguigu.gmall.oms.vo.OrderItemVo;
import com.atguigu.gmall.oms.vo.OrderSubmitVo;
import com.atguigu.gmall.order.feign.*;
import com.atguigu.gmall.order.interceptors.LoginInterceptor;
import com.atguigu.gmall.order.vo.OrderConfirmVo;
import com.atguigu.gmall.pms.entity.SkuAttrValueEntity;
import com.atguigu.gmall.pms.entity.SkuEntity;
import com.atguigu.gmall.sms.vo.ItemSaleVo;
import com.atguigu.gmall.ums.entity.UserAddressEntity;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.atguigu.gmall.wms.vo.SkuLockVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderService {

    @Autowired
    private GmallPmsClient pmsClient;

    @Autowired
    private GmallCartClient cartClient;

    @Autowired
    private GmallSmsClient smsClient;

    @Autowired
    private GmallWmsClient wmsClient;

    @Autowired
    private GmallUmsClient umsClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ExecutorService executorService;

    @Autowired
    private GmallOmsClient omsClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final String KEY_PREFIX = "order:token:";

    public OrderConfirmVo confirm() {
        OrderConfirmVo confirmVo = new OrderConfirmVo();

        // 通过拦截器获取userId
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();

        // 根据userId查询收获地址列表
        CompletableFuture<Void> addressesFuture = CompletableFuture.runAsync(() ->{
            ResponseVo<List<UserAddressEntity>> userResponseVo = umsClient.queryAddressesByUserId(userId);
            List<UserAddressEntity> addresses = userResponseVo.getData();
            confirmVo.setAddresses(addresses);
        },executorService);


        // 根据userId查询已选中的购物车记录
        CompletableFuture<List<Cart>> cartsFuture = CompletableFuture.supplyAsync(() ->{
            ResponseVo<List<Cart>> cartResponseVo = cartClient.queryCheckedCartsByUserId(userId);
            List<Cart> carts = cartResponseVo.getData();
            if (CollectionUtils.isEmpty(carts)) {
                throw new OrderException("您没有选中的购物车信息");
            }
            return carts;
        }, executorService);
        CompletableFuture<Void> itemFuture = cartsFuture.thenAcceptAsync(carts -> {
            List<OrderItemVo> items = carts.stream().map(cart -> {
                OrderItemVo orderItemVo = new OrderItemVo();
                Long skuId = cart.getSkuId();

                // 直接设置skuId和count
                orderItemVo.setSkuId(skuId);
                orderItemVo.setCount(cart.getCount());

                //根据skuId查询sku
                CompletableFuture<Void> skuFuture = CompletableFuture.runAsync(() -> {
                    ResponseVo<SkuEntity> skuEntityResponseVo = pmsClient.querySkuById(skuId);
                    SkuEntity skuEntity = skuEntityResponseVo.getData();
                    orderItemVo.setDefaultImage(skuEntity.getDefaultImage());
                    orderItemVo.setPrice(skuEntity.getPrice());
                    orderItemVo.setWeight(skuEntity.getWeight());
                    orderItemVo.setTitle(skuEntity.getTitle());
                }, executorService);

                // 根据skuId查询销售属性
                CompletableFuture<Void> saleAttrsFuture = CompletableFuture.runAsync(() -> {
                    ResponseVo<List<SkuAttrValueEntity>> saleAttrValuesResponseVo = pmsClient.querySaleAttrValuesBySkuId(skuId);
                    List<SkuAttrValueEntity> skuAttrValues = saleAttrValuesResponseVo.getData();
                    orderItemVo.setSaleAttrs(skuAttrValues);
                }, executorService);

                // 根据skuId查询营销信息
                CompletableFuture<Void> saleFuture = CompletableFuture.runAsync(() -> {
                    ResponseVo<List<ItemSaleVo>> salesResponseVo = smsClient.querySalesBySkuId(skuId);
                    List<ItemSaleVo> itemSaleVos = salesResponseVo.getData();
                    orderItemVo.setSales(itemSaleVos);
                }, executorService);

                // 根据skuId查询库存
                CompletableFuture<Void> storeFuture = CompletableFuture.runAsync(() -> {
                    ResponseVo<List<WareSkuEntity>> wareResponseVo = wmsClient.queryWareSkusBySkuId(skuId);
                    List<WareSkuEntity> wareSkuEntities = wareResponseVo.getData();
                    if (!CollectionUtils.isEmpty(wareSkuEntities)) {
                        orderItemVo.setStore(wareSkuEntities.stream().anyMatch(wareSkuEntity -> wareSkuEntity.getStock() > wareSkuEntity.getStockLocked()));
                    }
                }, executorService);

                CompletableFuture.allOf(skuFuture,saleAttrsFuture,saleFuture,storeFuture).join();
                return orderItemVo;
            }).collect(Collectors.toList());
            confirmVo.setItems(items);
        }, executorService);

        // 根据userId查询用户
        CompletableFuture<Void> boundFuture = CompletableFuture.runAsync(() -> {
            ResponseVo<UserEntity> userEntityResponseVo = umsClient.queryUserById(userId);
            UserEntity userEntity = userEntityResponseVo.getData();
            if (userEntity != null) {
                confirmVo.setBounds(userEntity.getIntegration());
            }
        }, executorService);

        // 为了防重，生成一个唯一标识，设置给confirmVo，并保存到redis
        CompletableFuture<Void> orderTokenFuture = CompletableFuture.runAsync(() -> {
            String orderToken = IdWorker.getIdStr();
            confirmVo.setOrderToken(orderToken);
            redisTemplate.opsForValue().set(KEY_PREFIX + orderToken,orderToken,3, TimeUnit.HOURS);
        }, executorService);

        CompletableFuture.allOf(addressesFuture,itemFuture,boundFuture,orderTokenFuture).join();
        return confirmVo;
    }

    public void submit(OrderSubmitVo submitVo) {
        // 1.防重  取页面中的orderToken（submitVo中的orderToken） 判断redis中是否存在（立刻删除，保证原子性）
        String orderToken = submitVo.getOrderToken();
        if (StringUtils.isBlank(orderToken)) {
            throw new OrderException("请求非法！");
        }
        String script = "if(redis.call('get', KEYS[1]) == ARGV[1]) " +
                "then return redis.call('del', KEYS[1]) " +
                "else return 0 " +
                "end";
        boolean flag = redisTemplate.execute(new DefaultRedisScript<>(script,Boolean.class),
                Arrays.asList(  KEY_PREFIX + orderToken), orderToken);
        if (!flag) {
            throw new OrderException("请不要重复提交或者当前页面已过期");
        }

        // 2.验总价 判断页面中的总价格 和 数据库中的实时总价格是否相同
        BigDecimal totalPrice = submitVo.getTotalPrice();
        List<OrderItemVo> items = submitVo.getItems();
        if (CollectionUtils.isEmpty(items)) {
            throw new OrderException("没有要购买的商品");
        }
        BigDecimal currentTotalPrice = items.stream().map(orderItemVo -> {
            ResponseVo<SkuEntity> skuEntityResponseVo = pmsClient.querySkuById(orderItemVo.getSkuId());
            SkuEntity skuEntity = skuEntityResponseVo.getData();
            if (skuEntity == null) {
                return new BigDecimal(0);
            }
            return skuEntity.getPrice().multiply(orderItemVo.getCount()); // 单价×数量
        }).reduce((a,b) -> a.add(b)).get();
        if (totalPrice.compareTo(currentTotalPrice) != 0){
            throw new OrderException("页面已过期，请刷新重试");
        }
        // 3.验库存，锁库存（保证原子性）
        List<SkuLockVo> skuLockVos = items.stream().map(orderItemVo -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItemVo.getSkuId());
            skuLockVo.setCount(orderItemVo.getCount().intValue());
            return skuLockVo;
        }).collect(Collectors.toList());
        ResponseVo<List<SkuLockVo>> res = wmsClient.checkLock(skuLockVos, orderToken);
        List<SkuLockVo> lockVos = res.getData();
        if (!CollectionUtils.isEmpty(lockVos)) {
            throw new OrderException(JSON.toJSONString(lockVos));
        }

        // 4.创建订单
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();

        try {
            omsClient.saveOrder(submitVo,userId);
            // 订单创建成功之后，发送延时消息，定时关单
            rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "order.ttl", orderToken);
        } catch (Exception e) {
            e.printStackTrace();
            // 标记订单为无效订单，并解锁库存
            rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "order.failure", orderToken);
            throw new OrderException("服务器内部错误");
        }

        // 5.异步删除购物车中对应的商品
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", userId);
        List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
        msg.put("skuIds",JSON.toJSONString(skuIds));
        rabbitTemplate.convertAndSend("ORDER_EXCHANGE", "cart.delete", msg);
    }
}
